package cn.org.july.weixin.controller;

import cn.org.july.weixin.common.bean.AccessAuthenticationBean;
import cn.org.july.weixin.common.constant.WxConstant;
import cn.org.july.weixin.common.exception.ErrorCode;
import cn.org.july.weixin.common.utils.XmlUtils;
import cn.org.july.weixin.service.WxService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @auther: wanghongjie
 * @blame: wanghongjie
 * @date: 2020-08-29 10:14
 * @Description:
 */
@Slf4j
@RestController
@RequestMapping("/wx/access")
public class WxController {

    @Autowired
    private WxService wxService;

    @GetMapping
    public String accessAuthentication(@RequestParam String signature,
                                       @RequestParam String timestamp,
                                       @RequestParam String nonce,
                                       @RequestParam String echostr) {
        AccessAuthenticationBean authenticationBean = AccessAuthenticationBean.of(signature, timestamp, nonce, echostr);
        log.info("=============初始化微信公众号================");
        if (authenticationBean.check(WxConstant.TOKEN)) {
            log.info("=============初始化微信公众号[成功]============");
            return authenticationBean.getEchoStr();
        } else {
            log.info("=============初始化微信公众号[失败]============");
            return ErrorCode.SUCCESS.name();
        }
    }

    @PostMapping
    public String getMessage(@RequestBody String message) throws Exception {
        log.info("Wx request message is {}", message);
        Map<String, Object> param = XmlUtils.xmlStrToMap(message);
        assert param != null;
        String type = param.get(WxConstant.MSG_TYPE).toString();
        return wxService.initialize(type, param);
    }


}
